﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace UI
{
    public partial class FrmMapOutput : Form 
    {
        

        FrmTreeView Legend;
        FrmTreeView Layers;
        FrmMapImage Map;

        void SelectLabelFile(object o, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string[] Content = new List<string>(System.IO.File.ReadAllLines(dlg.FileName).Where(line=>line.Length >0)).ToArray();
                foreach (string line in Content)
                {
                    string key = line.Split(new char[] { ',', '\t' }, StringSplitOptions.RemoveEmptyEntries)[0];
                    string value = line.Split(new char[] { ',', '\t' }, StringSplitOptions.RemoveEmptyEntries)[1];

                    if (Legend.ContainsText(key))
                    {
                        Legend.ChangeNodeText(key, value);
                        Legend.Update();
                    }
                }

            }
        }

      
        public FrmMapOutput(string text)
        {
            InitializeComponent();

            this.Text = text;

            Legend = new FrmTreeView("Legend");
            
            Legend.AddContextMenuItem("Select label file", SelectLabelFile);

            this.timer1.Interval = 10;
            this.timer1.Start();

            dockContainer1.DockForm(dockContainer1.Add(Legend, Crom.Controls.Docking.zAllowedDock.Right, Guid.NewGuid()), DockStyle.Right, Crom.Controls.Docking.zDockMode.Outer);

            Layers = new FrmTreeView("Layers");

            Layers.CheckBoxUpdate += new EventHandler<TreeViewEventArgs>(treeView_Layers_AfterCheck);

            Layers.CheckBoxes = true; 

            dockContainer1.DockForm(dockContainer1.Add(Layers, Crom.Controls.Docking.zAllowedDock.Left, Guid.NewGuid()), DockStyle.Left, Crom.Controls.Docking.zDockMode.Outer);

            Map = new FrmMapImage("Map");

            Map.PlayAnimation += new EventHandler(PlayAnimation);

            dockContainer1.DockForm(dockContainer1.Add(Map, Crom.Controls.Docking.zAllowedDock.Fill, Guid.NewGuid()), DockStyle.Fill, Crom.Controls.Docking.zDockMode.None);

        }
        
        private void MySendMessage(string msg)
        {
            if (this.SendMessage != null)
            {
                this.SendMessage((object)msg, new EventArgs());
            }
        }
        public bool IsInDockContainer
        {
            get;
            set;
        }

        public event EventHandler SendMessage;

        void SelectLayer(TreeViewEventArgs e)
        {
            if (e.Action != TreeViewAction.Unknown)
            {
                for (int layer = 0; layer < Map.LayerCount; layer++)
                {
                    int LayerHandle = Map.get_LayerHandle(layer);

                    string LayerName = Map.LayerName(LayerHandle);

                    if (LayerName == e.Node.Tag.ToString())
                    {
                        Map.set_LayerVisible(LayerHandle, true);
                    }
                    else
                    {
                        Map.set_LayerVisible(LayerHandle, false);
                    }
                }
            }
        }
        void SelectLayerNode(TreeViewEventArgs e)
        {
            //Null check makes sure the main page is attached to the event
            if (e.Action != TreeViewAction.Unknown)
            {
                foreach (TreeNode node in Layers.Nodes)
                {
                    if (node == e.Node) node.Checked = true;
                    else node.Checked = false;
                }
            }
        }
        List<string> FileNames = new List<string>();

        public void AddLayerData(string FileName)
        {
            FileNames.Add(FileName);
        }

        public void PlayAnimation(object sender, EventArgs e)
        {
            foreach (TreeNode tree_node in Layers.Nodes)
            {
                SelectLayer(new TreeViewEventArgs(tree_node, TreeViewAction.ByMouse));
                SelectLayerNode(new TreeViewEventArgs(tree_node, TreeViewAction.ByMouse));

                Map.Invalidate();
                Map.Refresh();

                Layers.Invalidate();
                Layers.Refresh();

                System.Threading.Thread.Sleep(2000);
            }
        }
       

        private void treeView_Layers_AfterCheck(object sender, TreeViewEventArgs e)
        {
            SelectLayer(e);
            SelectLayerNode(e);

        }
        
        public int get_Year(string FileName)
        {
            int year = -1;
            if (int.TryParse(System.Text.RegularExpressions.Regex.Match(FileName, @"\d+").Value, out year))
            {
                return year;
            }
            return year;
        }
        void ApplyColorSchemeToLegend(MapWinGIS.GridColorScheme colorscheme)
        {
            Legend.ClearNodes();

            for (int i = 0; i < colorscheme.NumBreaks; i++)
            {
                MapWinGIS.GridColorBreak colorbreak = colorscheme.get_Break(i);

                string Label =null;
                if (colorbreak.HighValue - colorbreak.LowValue <= 1)
                {
                    Label = colorbreak.LowValue.ToString();
                }
                else 
                {
                    Label = colorbreak.LowValue.ToString() + "-" + colorbreak.HighValue.ToString();
                }

                Legend.AddNode((int)colorbreak.LowValue, Label, null, null  , Legend.NodeRect(Legend.Font, Color.UIntToColor(colorbreak.HighColor)));
            }
        }
         
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           // MySendMessage("Checking incoming files");
            if(FileNames.Count() >0)
            {
                MySendMessage("Adding maplayer " + FileNames[0]);

                string LayerName = System.IO.Path.GetFileNameWithoutExtension(FileNames[0]);
                //get_LayerName(FileNames[0]);

                Map.AddLayer(FileNames[0], LayerName);

                ApplyColorSchemeToLegend(Map.GridColorscheme);

                string NodeText = System.IO.Path.GetFileNameWithoutExtension(FileNames[0]);
                string TipToolText = FileNames[0];
                Layers.AddNode(get_Year(FileNames[0]), NodeText, TipToolText, LayerName, null);

                SelectLayer(new TreeViewEventArgs(Layers.Nodes[Layers.Nodes.Count - 1], TreeViewAction.ByMouse));
                SelectLayerNode(new TreeViewEventArgs(Layers.Nodes[Layers.Nodes.Count - 1], TreeViewAction.ByMouse));

                FileNames.RemoveAt(0);
                
            }
            //MySendMessage("Ready adding incoming files");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy == false)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }
    }
}
